<?php

namespace app\index\controller;

use app\index\job\JobActivity;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;

class Api extends Controller
{
    // 后台分配任务给陪诊员
    public function chooseUser()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');
        if (empty($user_id)) apiReturn(2, '陪诊员ID缺失');

        $count = Db::name('plan')->where(['order_id' => $id])->count();
        if ($count > 0) apiReturn(2, '操作失败，该订单已被分配');

        $info = Db::name('order')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $data = [
                    'user_id' => $user_id,
                    'order_id' => $id,
                    'service_id' => $info['service_id'],
                    'status' => 1,
                    'create_time' => time()
                ];
                Db::name('plan')->insert($data);

                Db::name('order')->where(['id' => $id])->update(['status' => 1]);

                Db::commit();
                apiReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '操作失败');
            }


        } else {
            apiReturn(2, '订单不存在');
        }
    }

    /**
     * 生成省市联动数据文件
     * */
    public function createRegionFile()
    {
        $region_list = Db::name('province')->field('province_id id,name')->order('province_id asc')->select();
        if ($region_list) {
            foreach ($region_list as &$v) {
                $city_list = Db::name('city')->field('city_id id,name,province_id pid')->where(['province_id' => $v['id']])->order('city_id asc')->select();
                $v['city_list'] = $city_list ? : [];
            }
        }

        file_put_contents(RUNTIME_PATH . 'region.json', json_encode($region_list, JSON_UNESCAPED_UNICODE));
    }

    public function openidToUserid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(httpsRequest($url));

        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~');

        $openid = $user_data->openid;

        if (empty($openid)) apiReturn(2, '登录失败');

        $user_id = Db::name('user')->where(['openid' => $openid])->value('id');

        if ($user_id) {
            apiReturn(1, '登录成功', $user_id);
        } else {
            apiReturn(2, '新用户，走注册流程');
        }
    }

    /**
     * 获取openid
     */
    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $json_res = httpsRequest($url);
        $user_data = json_decode($json_res);

        if ($openid = $user_data->openid) {
            apiReturn(1, '获取数据成功', $openid);
        } else {
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();
        file_put_contents(RUNTIME_PATH . 'getMobileParam.txt', json_encode($input, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);

        $code = $input['code'];

        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

        $token = get_access_token('xcx_access_token.json', 2);
        if (empty($token)) apiReturn(2, 'TOKEN缺失');

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        $result = json_decode($result, true);

        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];

            if ($mobile) {
                file_put_contents(RUNTIME_PATH . 'mobile_success.txt', 'errcode == 0   ===>   ' . $mobile . PHP_EOL, FILE_APPEND);
                apiReturn(1, '获取数据成功', $mobile);
            } else {
                file_put_contents(RUNTIME_PATH . 'mobile_error.txt', 'errcode == 0   ===>   ' . json_encode($result, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            file_put_contents(RUNTIME_PATH . 'mobile_error.txt', 'errcode != 0   ===>   ' . json_encode($result, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            if ($result['errcode'] == 40001) {
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }

    /**
     * 登录
     * */
    public function login()
    {
        $input = Request()->param();

        $openid = $input['openid'];
        $avatar = $input['avatar'];
        $nickname = $input['nickname'];
        $mobile = $input['mobile'];

        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($avatar)) apiReturn(2, '请上传头像信息');
        if (empty($nickname)) apiReturn(2, '请填写昵称');
        if (empty($mobile)) apiReturn(2, '请获取手机号');

        $mobile_count = Db::name('user')->where(['mobile' => $mobile])->count();
        if ($mobile_count > 0) apiReturn(2, '该手机号已使用');

        Db::startTrans();
        try {
            $count = Db::name('user')->where(['openid' => $openid])->count();
            if ($count) {
                $user_id = Db::name('user')->where(['openid' => $openid])->value('id');
            } else {
                $data = [
                    'openid' => $openid,
                    'avatar' => $avatar,
                    'nickname' => $nickname,
                    'mobile' => $mobile,
                    'type' => 1,
                    'create_time' => time()
                ];

                $user_id = Db::name('user')->insertGetId($data);
            }

            Db::commit();
            apiReturn(1, '登录成功', $user_id);
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 首页接口
     * */
    public function index()
    {
        $input = Request()->param();

        $city_id = $input['city_id'] ? : 110000;// 默认北京市

        $banner = Db::name('banner')->order('id desc')->column('img');
        if ($banner) {
            foreach ($banner as &$v) {
                $v = getPicture($v);
            }
        }

        $config = Db::name('index_config')->value('config');
        $config = json_decode($config, true);
        if ($config) {
            foreach ($config as &$v) {
                $v['img'] = getHost() . $v['img'];
            }
        }

        $hospital_list = Db::name('hospital')->field('id,name,img,tags')->where('city_id', $city_id)->order('id asc')->select();
        if ($hospital_list) {
            foreach ($hospital_list as &$v) {
                $v['img'] = getPicture($v['img']);
                $v['tags'] = explode(',', $v['tags']);
            }
        }

        // 查询hospital表数据，city_id不重复
        $city_ids = Db::name('hospital')->group('city_id')->column('city_id');
        if ($city_ids) {
            $city_list = Db::name('city')->field('city_id,name')->whereIn('city_id', $city_ids)->order('city_id asc')->select();
        } else {
            $city_list = [];
        }

        $data = [
            'banner' => $banner,
            'config' => $config,
            'hospital_list' => $hospital_list,
            'city_list' => $city_list
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 医院详情
     * */
    public function hospitalInfo()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '医院ID缺失');

        $info = Db::name('hospital')->field('id,name,img,tags,des')->where('id', $id)->find();
        if ($info) {
            $info['img'] = getPicture($info['img']);
            $info['tags'] = $info['tags'] ? explode(',', $info['tags']) : [];
            $info['des'] = doEditorContent($info['des']);

            $qr = Db::name('qr_code')->value('qr');
            $info['qr'] = getPicture($qr);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '医院不存在');
        }
    }

    /**
     * 服务分类列表
     * */
    public function serviceTypeList()
    {
        $list = Db::name('service_type')->field('id,name')->order('sort asc')->select();
        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 服务列表
     * */
    public function serviceList()
    {
        $input = Request()->param();

        $type_id = $input['type_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;


        if (empty($type_id)) apiReturn(2, '分类ID缺失');

        $list = Db::name('service')->field('id,name,img,price,des')->where(['type_id' => $type_id])->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 服务详情
     * */
    public function serviceDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '服务ID缺失');

        $info = Db::name('service')->field('id,name,price,des,basic_des,price_des,reserve_des')->where('id', $id)->find();
        if ($info) {
            $info['basic_des'] = doEditorContent($info['basic_des']);
            $info['price_des'] = doEditorContent($info['price_des']);
            $info['reserve_des'] = doEditorContent($info['reserve_des']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '服务不存在');
        }
    }

    /**
     * 立即购买
     * */
    public function pay()
    {
        $input = Request()->param();

        $id = $input['id'] ? : 0;// 订单id

        if($id){
            $info = Db::name('order')->where('id',$id)->find();
            if(!$info) apiReturn(2, '订单不存在');

            $user_id = $info['user_id'];
            $service_id = $info['service_id'];
            $hospital_id = $info['hospital_id'];
        }else{
            $user_id = $input['user_id'];
            $service_id = $input['service_id'];
            $hospital_id = $input['hospital_id'] ? : 0;

            if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        }

        if (empty($service_id)) apiReturn(2, '服务ID缺失');
        $user_info = Db::name('user')->field('id,openid')->where(['id' => $user_id])->find();
        if (empty($user_info) || !$user_info['openid']) apiReturn(2, '用户信息有误');
        $service_info = Db::name('service')->where(['id' => $service_id])->find();
        if (empty($service_info) || !$service_info['name'] || !$service_info['price']) apiReturn(2, '服务信息有误');

        $time = time();
        if ($service_info) {
            // 生成待支付订单
            if($id == 0){
                $order_sn = 'SN' . date('YmdHis', $time) . mt_rand(1000, 9999);
                $pay_price = $service_info['price'] > 0 ? $service_info['price'] : 0;

                $data = [
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'service_id' => $service_id,
                    'hospital_id' => $hospital_id,
                    'pay_order_sn' => $order_sn,
                    'all_price' => $pay_price,
                    'pay_price' => $pay_price,
                    'create_time' => $time
                ];
                Db::name('order')->insert($data);
            }else{
                $order_sn = $info['order_sn'];
                $pay_price = $info['pay_price'];
            }

            Loader::import('wxsdk\wxPay', EXTEND_PATH);
            $obj = new \wxPay();
            //调用示例（最后两个参数为可选参数）
            $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '购买服务', getHost() . '/Index/Notify/notice');

            if ($pay_data) {
                $data = [
                    'order_sn' => $order_sn,
                    'pay_data' => $pay_data
                ];
                Db::commit();
                apiReturn(1, '获取支付信息成功', $data);
            } else {
                Db::rollback();
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }

    /**
     * 订单列表
     * */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] != -1 ? $input['status'] : -1;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        if ($status != -1) $where['status'] = $status;

        $list = Db::name('order')->field('id,service_id,status,pay_price,pay_time')->where($where)->page($page, $pagesize)->order('id desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $service_name = Db::name('service')->where(['id' => $v['service_id']])->value('name');
                $v['service_name'] = $service_name;

                $v['status_desc'] = doOrderStatus($v['status']);
                $v['pay_time'] = timeFormat($v['pay_time'], 'Y-m-d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 取消订单
     * */
    public function cancelOrder()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('order')->where(['id' => $id])->setField('status', 4);
            if ($res) {
                apiReturn(1, '取消订单成功');
            } else {
                apiReturn(2, '取消订单失败');
            }
        } else {
            apiReturn(2, '订单不存在');
        }
    }

    /**
     * 订单详情
     * */
    public function orderDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->field('id,order_sn,user_id,service_id,status,pay_price,pay_time')->where('id', $id)->find();
        if ($info) {
            $info['pay_time'] = timeFormat($info['pay_time'], 'Y-m-d H:i');

            $service_name = Db::name('service')->where(['id' => $info['service_id']])->value('name');
            $info['service_name'] = $service_name;

            $status_desc = doOrderStatus($info['status']);
            $info['status_desc'] = $status_desc;

            $user_info = Db::name('user')->field('id,avatar,nickname,mobile')->where('id', $info['user_id'])->find();
            $user_info['avatar_path'] = doAvatar($user_info['avatar']);
            $info['user_info'] = $user_info;

            $staff_info = Db::name('plan p')->join('ac_user u', 'p.user_id = u.id', 'left')
                ->field('u.id,u.avatar,u.nickname,u.mobile')
                ->where('p.order_id', $info['id'])
                ->find();
            $info['staff_info'] = $staff_info ? : [];

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在');
        }
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $input = Request()->param();

        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $list = Db::name('article')->field('id,title,img,look_count,create_time')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
                $v['create_time'] = date('Y-m-d H:i', $v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 文章详情
     * */
    public function articleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];
        $type = $input['type'] ? : 0;

        if ($id && $type == 0) {
            if (empty($id)) apiReturn(2, '文章ID缺失');
            $db = 'article';
            $where['id'] = $id;
        } else {
            $db = 'article_other';
            $where['id'] = 1;
        }

        $info = Db::name($db)->field('id,title,content,create_time')->where($where)->find();
        if ($info) {
            if ($type == 0) Db::name('article')->where('id', $id)->setInc('look_count');

            $info['create_time'] = timeFormat($info['create_time'], 'Y-m-d H:i');
            $info['content'] = doEditorContent($info['content']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在');
        }
    }

    /**
     * 获取职业
     * */
    public function getWorkConfig()
    {
        $work = array_values(array_filter(C('WORK')));

        apiReturn(1, '获取数据成功', $work);
    }

    /**
     * 用户信息
     * */
    public function userCenter()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('user')->field('id,nickname,avatar,mobile,type,examine_status,refuse_reason')->where('id', $user_id)->find();
        if ($info) {
            if ($info['status'] == 2) apiReturn(2, '账号已被禁用');

            $info['avatar_path'] = doAvatar($info['avatar']);

            $user_extend = Db::name('user_extend')->where(['user_id' => $user_id])->find();
            $info['user_extend'] = $user_extend ? : [];

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '获取数据失败');
        }
    }

    /**
     * 申请成为陪诊员回显数据
     * */
    public function applyPageData()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $work = array_values(array_filter(C('WORK')));
        $info = Db::name('user_extend')->where(['user_id' => $user_id])->find();

        $work_index = 0;
        if ($info) {
            $info['card_z_path'] = getPicture($info['card_z']);
            $info['card_f_path'] = getPicture($info['card_f']);

            $examine_status = Db::name('user')->where(['id' => $user_id])->value('examine_status');
            $info['examine_status'] = $examine_status;

            // 查询$info['work']在$work数组中的下标
            $work_index = array_search($info['work'], $work);
        }

        $data = [
            'work' => $work,
            'work_index' => $work_index > -1 ? $work_index : 0,
            'info' => $info ? : []
        ];
        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 申请成为陪诊员
     * */
    public function applyUserExtend()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $work = $input['work'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        $wx = $input['wx'];
        $province_id = $input['province_id'];
        $city_id = $input['city_id'];
        $province_name = $input['province_name'];
        $city_name = $input['city_name'];
        $address = $input['address'];
        $card_z = $input['card_z'];
        $card_f = $input['card_f'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($work)) apiReturn(2, '请选择职业');
        if (empty($username)) apiReturn(2, '请输入姓名');
        if (empty($mobile)) apiReturn(2, '请输入手机号');
        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) apiReturn(2, '手机号格式不正确');
        if (empty($wx)) apiReturn(2, '请输入微信号');
        if (empty($province_id) || empty($city_id)) apiReturn(2, '请现在城市');
        if (empty($address)) apiReturn(2, '请输入所在地区');
        if (empty($card_z) || empty($card_f)) apiReturn(2, '请上传身份证正反面照片');

        $mobile_count = Db::name('user_extend')->where(['mobile' => $mobile, 'user_id' => ['neq', $user_id]])->count();
        if ($mobile_count > 0) apiReturn(2, '手机号已存在');

        $count = Db::name('user_extend')->where(['user_id' => $user_id])->count();

        $data = [
            'user_id' => $user_id,
            'work' => $work,
            'username' => $username,
            'mobile' => $mobile,
            'wx' => $wx,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'province_name' => $province_name,
            'city_name' => $city_name,
            'address' => $address,
            'card_z' => $card_z,
            'card_f' => $card_f
        ];

        Db::startTrans();;
        try {
            if ($count > 0) {
                // 修改
                $data['update_time'] = time();

                Db::name('user_extend')->where(['user_id' => $user_id])->update($data);
            } else {
                // 新增
                $data['create_time'] = time();
                Db::name('user_extend')->insert($data);
            }

            Db::name('user')->where(['id' => $user_id])->setField('examine_status', 0);

            Db::commit();
            apiReturn(1, '提交成功');
        } catch (\Exception $e) {
            Db::rollback();

            apiReturn(2, '提交失败', $e->getMessage());
        }
    }

    /**
     * 任务列表
     * */
    public function planList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        if ($status > 0) $where['status'] = $status;

        $list = Db::name('plan')->field('id,user_id,service_id,order_id,status,create_time')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d H:i');
                $v['status_desc'] = doPlanStatus($v['status']);

                $service_name = Db::name('service')->where(['id' => $v['service_id']])->value('name');
                $v['service_name'] = $service_name;

                $user_info = Db::name('user u')->join('ac_order o', 'u.id = o.user_id')->where(['o.id' => $v['order_id']])->field('u.nickname,u.mobile')->find();
                $v['user_info'] = $user_info;
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 申请完成【任务变为审核中状态】
     * */
    public function applyComplete()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '参数错误');

        $info = Db::name('plan')->where(['id' => $id])->find();
        if (empty($info)) apiReturn(2, '任务不存在');

        if ($info['status'] != 1) apiReturn(2, '任务状态错误');

        $res = Db::name('plan')->where(['id' => $id])->setField('status', 2);
        if ($res) {
            apiReturn(1, '申请成功');
        } else {
            apiReturn(2, '操作失败');
        }
    }
}
